package com.app.util;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Calendar;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.app.dto.SendReq;
import com.app.dto.SendRes;
import org.apache.commons.codec.binary.Base64;

import com.alibaba.fastjson.JSON;


/**
 * 其他功能尚未发现
 *
 * @Description:
 * @Author: N
 * @Date: 2022/10/18 17:17
 */
public class SMSUtils {
    private static String apId = "hwsc";
    private static String secretKey = "Msjy_0626";
    private static String ecName = "肃州区就业服务中心";    //集团名称
    private static String sign = "jx7nbz8uI";    //网关签名编码
    private static String addSerial = "";    //拓展码 填空
    private static String templateId = "ed128e2736694688b040b56324bcbc0e";//验证码

    private static String deliverTemplateId = "0668fe3663e149e9b18fa1bab9670af6";//个人投递简历成功后

    private static String examineTemplateId = "e674a8369d524583bec50278b1a09d37";//招聘人员审核通过后

    private static String unemployedTemplateId = "1e94afa59d39407ca9853ed449a84baa";//未就业人员

    private static String videoTemplateId = "4561eea6f985408fabf19e9873d119d3";//视频面试预约成功后

    private static String enterpriseTemplateId = "527a0b3d5a16479e81190a54cb165046";//企业招聘

    private static String iTemplateId = "763c9b0b0ee448acb3f11028f6f7efa1";//个人求职

    private static String postTemplateId = "35ed37d9a6d645f6a195d74e8f139eb0";//岗位审核通过后


    public static String url = "http://112.35.1.155:1992/sms/tmpsubmit";//请求url


    public static void main(String[] args) throws IOException {
        post("17621541803");
    }

    /**
     * 登录验证码
     *
     * @throws IOException
     */
    public static void code(String mobiles,Integer mobileCode) throws IOException {
        String[] params = {String.valueOf(mobileCode)};
        sendMsg(mobiles, templateId, params);
    }

    /**
     * 个人投递简历成功后
     *
     * @throws IOException
     */
    public static void deliver(String mobiles) throws IOException {
        String[] params = {String.valueOf("")};
        sendMsg(mobiles, deliverTemplateId, params);
    }

    /**
     * 招聘人员审核通过后
     *
     * @throws IOException
     */
    public static void examine(String mobiles) throws IOException {
        String[] params = {String.valueOf("")};
        sendMsg(mobiles, examineTemplateId, params);
    }

    /**
     * 未就业人员
     *
     * @throws IOException
     */
    public static void unemployed(String mobiles) throws IOException {
        String[] params = {String.valueOf("")};
        sendMsg(mobiles, unemployedTemplateId, params);
    }

    /**
     * 视频面试预约成功后
     *
     * @throws IOException
     */
    public static void video(String mobiles, String comName, String time) throws IOException {

        String[] params = {comName, time};
        sendMsg(mobiles, videoTemplateId, params);
    }

    /**
     * 企业招聘
     *
     * @throws IOException
     */
    public static void enterprise(String mobiles) throws IOException {
        String[] params = {String.valueOf("")};
        sendMsg(mobiles, enterpriseTemplateId, params);
    }

    /**
     * 个人求职
     *
     * @throws IOException
     */
    public static void customer(String mobiles) throws IOException {
        String[] params = {String.valueOf("")};
        sendMsg(mobiles, iTemplateId, params);
    }

    /**
     * 岗位审核通过后
     *
     * @throws IOException
     */
    public static void post(String mobiles) throws IOException {
        String[] params = {String.valueOf("")};
        sendMsg(mobiles, postTemplateId, params);
    }

    /**
     * 多用户发送短信信息
     *
     * @param mobiles    手机号码逗号分隔
     * @param templateId 短信模板
     * @return 返回1表示成功，0表示失败
     * @throws IOException
     */
    public static int sendMsg(String mobiles, String templateId, String[] params) throws IOException {
        Calendar calendar = Calendar.getInstance();

        SendReq sendReq = new SendReq();
        sendReq.setApId(apId);
        sendReq.setEcName(ecName);
        sendReq.setSecretKey(secretKey);
        sendReq.setTemplateId(templateId);
        sendReq.setMobiles(mobiles);
        sendReq.setParams(JSON.toJSONString(params));
        sendReq.setAddSerial(addSerial);
        sendReq.setSign(sign);

        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append(sendReq.getEcName());
        stringBuffer.append(sendReq.getApId());
        stringBuffer.append(sendReq.getSecretKey());
        stringBuffer.append(sendReq.getTemplateId());
        stringBuffer.append(sendReq.getMobiles());
        stringBuffer.append(sendReq.getParams());
//        List<String> list = Arrays.asList(params);
//        String joined = list.stream()
//                .map(s -> "\"" + s + "\"") // 在每个元素前后添加双引号
//                .collect(Collectors.joining(", ")); // 用逗号分隔连接字符串
//        stringBuffer.append("[").append(joined).append("]");

        stringBuffer.append(sendReq.getSign());
        stringBuffer.append(sendReq.getAddSerial());
        String str = sendReq.getEcName();

        //System.out.println(stringBuffer.toString());
        sendReq.setMac(Md5Util.MD5(stringBuffer.toString()).toLowerCase());
        //System.out.println(sendReq.getMac());

        String reqText = JSON.toJSONString(sendReq);

        String encode = Base64.encodeBase64String(reqText.getBytes("UTF-8"));
        //System.out.println(encode);

        String resStr = sendPost(url, encode);

        System.out.println("发送短信结果：" + resStr);

        SendRes sendRes = JSON.parseObject(resStr, SendRes.class);

        if (sendRes.isSuccess() && !"".equals(sendRes.getMsgGroup()) && "success".equals(sendRes.getRspcod())) {
            return 1;
        } else {
            return 0;
        }
    }

  /*
    //main方法测试发送短信，返回1表示成功，0表示失败
   	public static void main(String[] args) throws IOException{
    	String msg = "这是发送短信的内容！";
    	int result = sendMsg("183xxxx65xx,183xxxx12xx",msg);
        System.out.println("==="+result);
    }*/

    /**
     * 向指定 URL 发送POST方法的请求
     *
     * @param url   发送请求的 URL
     * @param param 请求参数
     * @return 所代表远程资源的响应结果
     */
    private static String sendPost(String url, String param) {
        OutputStreamWriter out = null;

        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            URLConnection conn = realUrl.openConnection();
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("contentType", "utf-8");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
            conn.setDoOutput(true);
            conn.setDoInput(true);

            out = new OutputStreamWriter(conn.getOutputStream());
            out.write(param);
            out.flush();


            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += "\n" + line;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return result;
    }

}
